package com.ultron.core.component.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.ultron.core.component.excel.ann.TitleColor;
import com.ultron.core.component.excel.handler.DropdownListSheetWriteHandler;
import com.ultron.core.component.excel.handler.TitleColorWriteHandler;
import com.ultron.core.component.excel.ann.DropExcelProperty;
import org.apache.poi.ss.usermodel.IndexedColors;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * excel工具，用于导出模版使用
 */
public class EasyExcelUtil {


    public static <T> ExcelWriterBuilder getExcelWriterBuilder(OutputStream outputStream, Class<T> tClass) {
        List<Field> fields = ColumnUtil.getFields(tClass);
        Map<Integer, IndexedColors> map = new HashMap<>();
        List<WriteHandler> handlers = fields.stream().map(f -> {
                    DropExcelProperty property = f.getDeclaredAnnotation(DropExcelProperty.class);
                    if (property != null) {
                        return new DropdownListSheetWriteHandler(property);
                    }
                    TitleColor titleColor = f.getDeclaredAnnotation(TitleColor.class);
                    if (titleColor != null) {
                        map.put(titleColor.col(), titleColor.color());
                    }
                    return null;
                }).filter(Objects::nonNull)
                .collect(Collectors.toList());

        ExcelWriterBuilder builder = EasyExcel.write(outputStream, tClass);
        for (WriteHandler handler : handlers) {
            builder.registerWriteHandler(handler);
        }
        if (map.size() > 0) {
            builder.registerWriteHandler(new TitleColorWriteHandler(map));
        }
        return builder;

    }


}
